import 'dart:convert';
import 'dart:io';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

class Utils {
  static Future<String> getImageBase64String(String imagePath) async {
    // 读取图像文件
    File imageFile = File(imagePath);
    if (!imageFile.existsSync()) {
      throw Exception("Image file not found");
    }
    // 读取图像文件的字节数组
    List<int> imageBytes = await imageFile.readAsBytes();
    // 将字节数组编码为Base64字符串
    String base64 = base64Encode(imageBytes);
    String base64Image = "data:image/png;base64,$base64";
    return base64Image;
  }

  static Future<String> openAlbum() async {
    XFile? image = await ImagePicker().pickImage(
      source: ImageSource.gallery,
      // maxHeight: 512.w,
      // maxWidth: 512.w,
    );
    if (image != null) {
      String base64 = await getImageBase64String(image.path);
      return base64;
    }
    return "";
  }

  static Future<String> openCamera() async {
    XFile? photo = await ImagePicker().pickImage(
      source: ImageSource.camera,
      maxHeight: 512.w,
      maxWidth: 512.w,
      preferredCameraDevice: CameraDevice.front,
    );
    if (photo != null) {
      String base64 = await getImageBase64String(photo.path);
      return base64;
    }
    return "";
  }


}
